package com.cola.utils.baiduMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cola.utils.HttpUtils;
import com.cola.utils.PropertyUtils;
import com.cola.utils.baiduMap.entity.BaiduMapResult;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * Created by Max on 2017/8/22.
 * 百度地图工具类
 */
public class BaiduMapUtils {
    private static final Logger logger= Logger.getLogger(BaiduMapUtils.class);

    private static double EARTH_RADIUS = 6378.137;
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 根据地址获取地理位置信息
     * @param address
     * @return
     */
    public static BaiduMapResult getLocationInfoByAddress(String address){
        StringBuilder postUrl = new StringBuilder(PropertyUtils.getProperty("baidu_map_geocoding_api"));

        postUrl.append("address=").append(address);

        postUrl.append("&output=json");

        postUrl.append("&ak=").append(PropertyUtils.getProperty("baidu_ak"));

        String result = HttpUtils.sendGet(postUrl.toString());

        Map<String,Object> resultMap = JSONObject.parseObject(result);

        if(Integer.parseInt(resultMap.get("status").toString())==0){
            return JSONObject.parseObject(result, BaiduMapResult.class);
        }else{
            return null;
        }
    }

    /**
     * 通过两地经纬度计算距离
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double getDistanceByLngAndLat(double lat1, double lng1, double lat2, double lng2){
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1-radLat2;
        double b = rad(lng1)-rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s* EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        return s;
    }

    public static void main(String[] args) {
        System.out.println(JSON.toJSONString(getLocationInfoByAddress("苏州观前街")));
//        System.out.println(getDistanceByLngAndLat(31.237077,121.47438, 31.240936, 121.488034));//baidu测距为1.4km,该方法为1368米
    }
}
